import { config } from "@vue/test-utils";
import axios from "axios";
import store from "@/store";
import { MessageBox, Message } from "element-ui";
import { getTimeDate } from "@/utils/auth";
import router from "@/router";
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
});

let timeOut = 3600;
// 请求拦截器
service.interceptors.request.use(async config => {
  if (store.getters.token) {
    let timeStamp = getTimeDate();
    let current = Date.now();
    let time = (current - timeStamp) / 1000;
    if (time >= timeOut) {
      await store.dispatch("user/logout");
      Message.error("登陆信息过期，请重新登陆");
      router.push("/login");
      return;
    }
    config.headers["Authorization"] = "Bearer " + store.getters.token;
  }
  return config;
});

// 响应拦截器
service.interceptors.response.use(
  response => {
    let res = response.data;

    if (res.success) {
      return res;
    } else {
      // 这次请求失败了，提示出失败原因
      Message.error(res.message);

      // 这句话会让代码报错
      return Promise.reject(res.message);
    }
  },
  error => {
    // 上一个项目是加在error
    // error要接口报错，没有正常返回才会进到error
    // console.dir(error);
    if (error.response.data.code == 10002) {
      store.dispatch("user/logout");
      Message.error("登陆信息过期，请重新登陆");
      router.push("/login");
    }
    return Promise.reject(error);
  }
);

export default service;
